package com.tang.core;

import com.tang.config.JwtAuthorizationConfig;
import com.tang.exceptions.MyAuthenticationEntryPoint;
import com.tang.filter.JwtTokenFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.context.NullSecurityContextRepository;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Tang
 * @classname WebSecurityConfig
 * @description [  ]
 * @date 2021/5/1 14:57
 */
@Configuration
public class WebSecurityConfig {

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true,jsr250Enabled = true,securedEnabled = true)
    @ConditionalOnProperty(prefix = "security",name = "type",havingValue = "true",matchIfMissing = true)
    static class DefaultWebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Resource
        private JwtAuthorizationConfig jwtAuthorizationConfig;

        /**
         * 各业务请求直接放行
         */
        @Value("#{'${security.auth.excludeUrls}'.split(',')}")
        private List<String> excludeUrls;

        @Override
        public void configure(WebSecurity web) throws Exception {
            super.configure(web);
        }

        /**
         * 默认的filter顺序参见{@code org.springframework.security.config.annotation.web.builders.FilterComparator}
         * @param http
         * @throws Exception
         */
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers(excludeUrls.toArray(new String[]{})).permitAll()
                    .anyRequest()
                    .authenticated()
                    .and()
                    // context默认存储为session,设置为
                    .securityContext().securityContextRepository(new NullSecurityContextRepository())
                    .and()
//                    .addFilterBefore(new GateWayTokenFilter(), BasicAuthenticationFilter.class)
                    .addFilterAfter(new JwtTokenFilter(jwtAuthorizationConfig), BasicAuthenticationFilter.class)
                    .exceptionHandling().authenticationEntryPoint(new MyAuthenticationEntryPoint())
                    .and()
                    .csrf()
                    .disable();
        }
    }

}